﻿package com.eightywork.life.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

public class HttpUtil {


	/**
	 * 判断是否有网络
	 * 
	 * @param context
	 * @return boolean 是否存在网络
	 */
	public static boolean haveConnection(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return false;
		} else if (!networkInfo.isAvailable()) {
			return false;
		}
		return true;
	}
	

	/**
	 * 判断网络类型
	 * 
	 * @param context
	 * @return String wifi or mobile
	 */
	public static String connectionType(Activity context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		String result = "";
		int type = networkInfo.getType();
		if (type == ConnectivityManager.TYPE_WIFI) {
			result = "wifi";
		} else if (type == ConnectivityManager.TYPE_MOBILE) {
			result = "mobile";
		}
		return result;
	}

	/**
	 * 通过HTTP协议post文件,参数
	 * 
	 * @param actionUrl
	 *            上传URL地址
	 * @param params
	 *            Map<String,String>参数, 没有参数的话传null
	 * @param files
	 *            Map<String,File>参数,没有参数的话传null
	 * @return String 返回页面的内容
	 * @throws IOException
	 */
	public static String post(String actionUrl, Map<String, String> params,
			Map<String, File> files) throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);
		// 首先组拼文本类型的参数
		StringBuilder sb = new StringBuilder();
		if (params != null) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINEND);
				sb.append("Content-Disposition: form-data; name=\""
						+ entry.getKey() + "\"" + LINEND);
				sb.append("Content-Type: text/plain; charset=" + CHARSET
						+ LINEND);
				sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
				sb.append(LINEND);
				sb.append(entry.getValue());
				sb.append(LINEND);
			}
		}
		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());
		outStream.write(sb.toString().getBytes("UTF-8"));

		// 发送文件数据
		if (files != null) {
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\""
						+ file.getKey() + "\"; filename=\""
						+ file.getValue().getPath() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset="
						+ CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes("UTF-8"));

				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024 * 50];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}

				is.close();
				outStream.write(LINEND.getBytes());
			}
		}

		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();

		// 得到响应码
		int res = conn.getResponseCode();
		StringBuilder sb2 = new StringBuilder();
		InputStream in = null;
		if (res == 200) {
			in = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in,
					"UTF-8"));
			String ch = null;
			while ((ch = br.readLine()) != null) {
				sb2.append(ch);
			}
		}
		return in == null ? "" : sb2.toString();
	}

	public static String post(String url, Map<String, String> map) throws MyHttpException  {
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			if (map != null) {
				for (Entry<String, String> set : map.entrySet()) {
					params.add(new BasicNameValuePair(set.getKey(), set
							.getValue()));
				}
			}
			HttpClient httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, 5000);
			HttpPost httpPost = new HttpPost(new URI(url.trim()));
			httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				return content.replaceAll("&nbsp;", "");
			}
		} catch (URISyntaxException ex) {
			ex.printStackTrace();
		} catch (ClientProtocolException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
			throw new MyHttpException("500", "网络异常请稍后再试");
		} 
		return "";
	}
	
	public static String get(String url, Map<String, String> map, String sessionId) throws MyHttpException{
		try {
			url += "?";
			if (map != null) {
				for (Entry<String, String> set : map.entrySet()) {
					url +=  set.getKey() + "=" +set
							.getValue() + "&"; 
				}
			}
			HttpClient httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, 5000);
			System.out.println("url---> " + url);
			HttpGet httpGet = new HttpGet(new URI(url.trim()));
			if(sessionId != null)
				httpGet.setHeader("Cookie", sessionId);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				return content.replaceAll("&nbsp;", "");
			}
		} catch (URISyntaxException ex) {
			ex.printStackTrace();
		} catch (ClientProtocolException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
			throw new MyHttpException("500", "网络异常请稍后再试");
		}
		return "";

	}
	
	public static String get(String url, Map<String, String> map) throws MyHttpException{
		return get(url, map, null);
	}
	
	public static String put(String url, Map<String, String> map) throws MyHttpException{
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			if (map != null) {
				for (Entry<String, String> set : map.entrySet()) {
					params.add(new BasicNameValuePair(set.getKey(), set
							.getValue()));
				}
			}
			HttpClient httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, 5000);
			HttpPut httpPut = new HttpPut(new URI(url));
			httpPut.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse httpResponse = httpClient.execute(httpPut);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				return content.replaceAll("&nbsp;", "");
			}
		} catch (URISyntaxException ex) {
			ex.printStackTrace();
		} catch (ClientProtocolException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
			throw new MyHttpException("500", "网络异常请稍后再试");
		} 
		return "";
	}
	
	public static String delete(String url, Map<String, String> map) throws MyHttpException{
		try {
			url += "?";
			if (map != null) {
				for (Entry<String, String> set : map.entrySet()) {
					url +=  set.getKey() + "=" +set
							.getValue() + "&"; 
				}
			}
			HttpClient httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, 5000);
			HttpDelete httpDelete = new HttpDelete(new URI(url));
			HttpResponse httpResponse = httpClient.execute(httpDelete);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(httpResponse.getEntity(),
						"UTF-8");
				return content.replaceAll("&nbsp;", "");
			}
		} catch (URISyntaxException ex) {
			ex.printStackTrace();
		} catch (ClientProtocolException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
			throw new MyHttpException("500", "网络异常请稍后再试");
		}
		return "";
	}
}
